<?php

class PersonaController extends AweController {

  /**
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   * using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout = '//layouts/column2';
  public $defaultAction = 'admin';

  public function filters() {
    return array(
        array('CrugeAccessControlFilter'),
    );
  }

  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id) {
    $this->render('view', array(
        'model' => $this->loadModel($id),
    ));
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate() {
    $model = new Persona;
    $result = array();
//        $model->Per_FecRegistro = Util::FechaActual();
    $this->performAjaxValidation($model, 'persona-form');
    if (Yii::app()->request->isAjaxRequest) {
      if (isset($_POST['ajax']) && $_POST['ajax'] === '#persona-form') {
        if (($_POST['Persona']['id_persona'] != null)) {
          $model = $this->loadModel($_POST['Persona']['id_persona']);
        }
        $model->attributes = $_POST['Persona'];
        $model->fecha_nacimiento = $_POST['Persona']['fecha_nacimiento'];

//        var_dump($model->fecha_nacimiento,$_POST['Persona']);
//        die();
        $validador = $this->Crear($model);
        $result['guardar'] = $validador;
        $result['success'] = $model->validate();
        $result['errors'] = $model->errors;
        echo json_encode($result);
        Yii::app()->end();
      }

      $validarPartial = false;
      if (isset($_POST['Persona'])) {
        $model->attributes = $_POST['Persona'];
        $result['success'] = $this->Crear($model);
        $result['id'] = $model->id_persona;
        $result['entidad_tipo'] = 'PERSONA';
        if ($result['success']) {
          $validarPartial = TRUE;
          echo json_encode($result);
        }
      }
    } else {
      if (isset($_POST['Persona'])) {
        $model->attributes = $_POST['Persona'];
//                $model->Per_FecNacimiento = Util::FormatDate($model->Per_FecNacimiento, 'Y-m-d');
        if ($model->save()) {
          $this->redirect(array('admin'));
        }
      }
      $this->render('create', array(
          'model' => $model,
      ));
    }
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id) {
    $model = $this->loadModel($id);
//        $model->Per_FecNacimiento = Util::FormatDate($model->Per_FecNacimiento, 'd/m/Y');
//        $model->Per_FecModificacion = Util::FechaActual();

    if (isset($_POST['ajax']) && $_POST['ajax'] === '#persona-form') {

      $model->attributes = $_POST['Persona'];
      $model->fecha_nacimiento = $_POST['Persona']['fecha_nacimiento'];

      $result['success'] = $model->validate();
      if (!$result['success']) {
        $result['errors'] = $model->errors;
        echo json_encode($result);
        Yii::app()->end();
      }
    }

    if (isset($_POST['Persona'])) {
      $model->attributes = $_POST['Persona'];
//            $model->Per_FecNacimiento = Util::FormatDate($model->Per_FecNacimiento, 'Y-m-d');
      $result['success'] = $model->save();
      if ($result['success']) {
        $b_guardado = array();
        $b_guardado['id_persona'] = $model->id_persona;
        $b_guardado['entidad_tipo'] = "PERSONA";
        $result['guardar'] = $b_guardado;
        echo CJSON::encode($result);
      }
    } else {
      $this->render('update', array(
          'model' => $model,
      ));
    }
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id) {
    if (Yii::app()->request->isPostRequest) {
      // we only allow deletion via POST request
      $this->loadModel($id)->delete();

      // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
      if (!isset($_GET['ajax']))
        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    } else
      throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
  }

  /**
   * Manages all models.
   */
  public function actionAdmin() {
    $model = new Persona('search');
    $model->unsetAttributes(); // clear any default values

    if (isset($_GET['search'])) {
      $model->attributes = $this->assignParams($_GET['search']);
    }

    if ($model->count() > 0) {
      $this->render('admin', array('model' => $model));
    } else {
      $this->render('empty');
    }
  }

//	public function actionAdmin()
//	{
//		$model = new Persona('search');
//		$model->unsetAttributes(); // clear any default values
//		if(isset($_GET['Persona']))
//			$model->attributes = $_GET['Persona'];
//
//		$this->render('admin', array(
//			'model' => $model,
//		));
//	}

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer the ID of the model to be loaded
   */
  public function loadModel($id, $modelClass = __CLASS__) {
    $model = Persona::model()->findByPk($id);
    if ($model === null)
      throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param CModel the model to be validated
   */
  protected function performAjaxValidation($model, $form = null) {
    if (isset($_POST['ajax']) && $_POST['ajax'] === 'persona-form') {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }

  public function assignParams($params) {
    $result = array();
//        var_dump($params);
    if ($params['filters'][0] == 'all') {
      foreach (Persona::model()->searchParams() as $param) {
        $result[$param] = $params['value'];
      }
    } else {
      foreach ($params['filters'] as $param) {
        $result[$param] = $params['value'];
      }
    }
    return $result;
  }

  private function Crear($model) {
    $b_guardado = array();
    $b_guardado['success'] = false;
    $b_guardado['success'] = $model->save();
    if ($b_guardado['success']) {
      $b_guardado['id_persona'] = $model->id_persona;
      $b_guardado['entidad_tipo'] = "PERSONA";
//            Actividad::registrarActividad($model, Actividad::TIPO_CREATE);
//            $asignadonuevo = $model->owner_id;
//            if ($asignadonuevo != Yii::app()->user->id) {
//                Alerta::registrarAlertaA($model, Alerta::ASIGNADO);
//            }
    } else {
      $b_guardado['messages'] = "No se a podido almacenar la persona.";
    }
    return $b_guardado;
  }

  public function actionAjaxlistContactos($search_value = null, $cuenta_id = null, $hasEmail = false) {
    if (Yii::app()->request->isAjaxRequest) {
      echo CJSON::encode(Persona::model()->getListSelect2($search_value, $cuenta_id, $hasEmail));
    }
  }

}
